package com.myblog.controller;

import com.myblog.constant.CodeType;
import com.myblog.model.Article;
import com.myblog.model.User;
import com.myblog.service.ArticleService;
import com.myblog.service.LikeService;
import com.myblog.service.TagService;
import com.myblog.service.UserService;
import com.myblog.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;

@Slf4j
@RestController
public class ArticleController {

    @Autowired
    private UserService userService;

    @Autowired
    private ArticleService articleService;

    @Autowired
    private TagService tagService;

    @Autowired
    private LikeService likeService;

    /**
     * 发布文章
     * @param article
     * @param articleGrade
     * @param request
     * @return
     */
    @PostMapping("/publishArticle")
    public String publicArticle(Article article, String articleGrade,
                                 HttpServletRequest request){
        try{
            //获取作者信息
//            String username = principal.getName();
            Principal userPrincipal = request.getUserPrincipal();
            User user = userService.searchUserByName(userPrincipal.getName());
            String username = user.getUsername();
//            String username = "匿名";
            //文章摘要 articleTabloid
            //很绝html中articleHtmlContent
            BuildArticleTabloidUtil buildArticleTabloidUtil = new BuildArticleTabloidUtil();
            String articleTabloid = buildArticleTabloidUtil.buildArticleTabloid(request.getParameter("articleHtmlContent"));
            article.setArticleTabloid(articleTabloid+"...");

            //对传递过来的标签进行处理
            String[] articleTags = request.getParameterValues("articleTagsValue");
            String[] newArticleTags = new String[articleTags.length];
            for (int i = 0; i < articleTags.length; i++) {
                //标签中的关键字，空格处理
                newArticleTags[i]=articleTags[i].replaceAll("<br>", StringUtil.BLANK).replaceAll("&nbsp;",StringUtil.BLANK)
                        .replaceAll("\\s",StringUtil.BLANK).trim();
            }
            tagService.insertTag(newArticleTags,Integer.parseInt(articleGrade));
            String tags = StringAndArray.arrayToString(newArticleTags);
            article.setArticleTags(tags);
            //调用service层的发布博客方法
            DataMap data = articleService.publicArticle(article,username);

            return JsonResult.build(data).toJSON();
        }catch (Exception e){
            log.error("ArticleAndTagsController publicArticle Exception",e);
        }
        return JsonResult.fail(CodeType.SERVER_EXCEPTION).toJSON();
    }

    /**
     * 后台文章管理获取文章分页查询
     * @param rows
     * @param pageNum
     * @return
     */
    @PostMapping("/getArticleManagement")
    public String getArticleByPage(@RequestParam("rows") Integer rows,@RequestParam("pageNum") Integer pageNum){
        try{
            //调用service层的发布博客方法
            DataMap data = articleService.getArticleByPage(rows,pageNum);
//            PageHelper.startPage(pageNum,rows);
//            PageInfo pageInfo = new PageInfo((List) data);
            return JsonResult.build(data).toJSON();
        }catch (Exception e){
            log.error("ArticleController getArticleByPage Exception",e);
        }
        return JsonResult.fail(CodeType.SERVER_EXCEPTION).toJSON();
    }

    /**
     * 后台管理删除文章
     * @param id
     * @return
     */
    @GetMapping("/deleteArticle")
    public String deleteById(@RequestParam("id")String id){
        try {
            DataMap data = articleService.deleteArticleById(Integer.valueOf(id));

            return JsonResult.build(data).toJSON();
        }catch (Exception e){
            log.error("ArticleAndTagsController deleteById Exception",e);
        }
        return JsonResult.fail(CodeType.SERVER_EXCEPTION).toJSON();
    }


    /**
     * 获取文章草稿
     * @param request
     * @return
     */
    @GetMapping("/getDraftArticle")
    public String getDraftArticle(HttpServletRequest request){
        try {
            Object attribute = request.getSession().getAttribute("id");
            if(attribute != null){
                Integer id =  Integer.parseInt((String)request.getSession().getAttribute("id"));
                DataMap data = articleService.getDraftArticleById(id);
                return JsonResult.build(data).toJSON();
            }
            else {
                JsonResult.fail(CodeType.ARTICLE_NOT_EXIST);
            }
        }catch (Exception e){
            log.error("ArticleAndTagsController getDraftArticle Exception",e);
        }
        return JsonResult.fail(CodeType.SERVER_EXCEPTION).toJSON();
    }

    /**
     * 主页获取文章列表
     * @param rows
     * @param pageNum
     * @return
     */
    @PostMapping("/myArticles")
    public String getMyArticle(@RequestParam("rows") Integer rows,@RequestParam("pageNum") Integer pageNum){
        try{
            //主页获得文章列表 调用service层的获取主页文章方法
            DataMap data = articleService.getArticleByPageIndex(rows,pageNum);

            return JsonResult.build(data).toJSON();
        }catch (Exception e){
            log.error("ArticleAndTagsController getMyArticle Exception",e);
        }
        return JsonResult.fail(CodeType.SERVER_EXCEPTION).toJSON();
    }

    /**
     * 搜索查看文章
     * @param rows
     * @param pageNum
     * @return
     */
    @PostMapping("/searchArticles")
    public String getSearchArticle(@RequestParam("rows") Integer rows,
                                   @RequestParam("pageNum") Integer pageNum,
                                   @RequestParam("searchContent") String Context){
        try{
            //主页获得文章列表 调用service层的获取主页文章方法
            DataMap data = articleService.getSearchArticleByPageIndex(rows,pageNum,Context);

            return JsonResult.build(data).toJSON();
        }catch (Exception e){
            log.error("ArticleAndTagsController getMyArticle Exception",e);
        }
        return JsonResult.fail(CodeType.SERVER_EXCEPTION).toJSON();
    }

    /**
     * 文章详情页面，通过文章id获取文章信息
     * @param articleId
     * @return
     */
    @PostMapping("/getArticleByArticleId")
    public String getArticleByArticleId(@RequestParam("articleId") String articleId,HttpServletRequest request){
        try{
            //获取点赞人
            Principal userPrincipal = request.getUserPrincipal();
            String userName = null;
            //判断用户是否已经点赞了文章
            Integer isLiked =0;
            if(userPrincipal != null){
                userName = userPrincipal.getName();
                //判断当前是否已经点赞，如果已经点赞了，返回fail
                if(likeService.isLike(Long.parseLong(articleId),userName)){
                    isLiked =1;
                }
            }
            DataMap data = articleService.getArticleByArticleId(Long.parseLong(articleId),isLiked);

            return JsonResult.build(data).toJSON();
        }catch (Exception e){
            log.error("ArticleAndTagsController getArticleByArticleId Exception",e);
        }
        return JsonResult.fail(CodeType.SERVER_EXCEPTION).toJSON();
    }




}
